<template>
  <div class="list">
    <ul>
      <li
        class="list__item"
        v-for="item in letters"
        :key="item.id"
        :ref="item"
        @click="handleLetterClick"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      >
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "CityAlphabet",
  props: {
    cities: Object,
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
    };
  },
  updated() {
    this.startY = this.$refs["A"][0].offsetTop;
  },
  computed: {
    letters() {
      const letters = [];
      for (let item in this.cities) {
        letters.push(item);
      }
      return letters;
    },
  },
  methods: {
    handleLetterClick(e) {
      // console.log("e.target", e.target);
      // 点击某个字母，向父组件发送该字母
      // innerText 和 innerHTML 是有区别的
      this.$emit("change", e.target.innerText);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        // 1. 计算第一个字母到页面组件顶部的距离
        // const startY = this.$refs["A"][0].offsetTop;
        this.timer = setTimeout(() => {
          // 2. 计算手指离页面组件顶部的距离
          const touchY = e.touches[0].clientY - 75;
          // 3. 计算差值，并除以字母的高度，得到手指触摸字母的下标
          const index = Math.floor((touchY - this.startY) / 20);
          // console.log(index);
          // 判断 index 值是否合理，再进行传值
          if (index >= 0 && index < this.letters.length) {
            // 将手指触摸到的字母传给父组件
            this.$emit("change", this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.5rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;
  &__item {
    line-height: 0.4rem;
    text-align: center;
    color: #00bcd4;
  }
}
</style>